<template>
  <div class="system-panel-wrapper user-wrapper">
    <search-form
      :search-fields="searchFields"
      :search-form="searchForm"
      :rules="userRule"
      @handle-search="handleSearch"
    />
    <datagrid
      max-height="calc(100% -50px)"
      :data-list="userlist"
      :columns="columns"
      :total="usertotal"
      :current-page="currentPage"
      :page-size="pageSize"
      :addable="true"
      :single-page-hide="false"
      @handle-size-change="handleSizeChange"
      @handle-current-change="handleCurrentChange"
      @handle-add="handleAdd"
      @change-switch="changeSwitch"
    >
      <el-table-column align="center" label="操作" width="270">
        <template slot-scope="scope">
          <span
            class="text-btn text-edit"
            @click="handleEdit(scope.$index, scope.row)"
          >
            编辑
          </span>
          <span
            class="text-btn text-edit"
            @click="handleChangePwd(scope.$index, scope.row)"
          >
            修改密码
          </span>
          <span
            v-if="scope.row.username !== 'admin'"
            class="text-btn text-delete"
            @click="handleDelete(scope.$index, userlist)"
          >
            删除
          </span>
        </template>
      </el-table-column>
    </datagrid>
    <!-- 新增/修改弹框 -->
    <dialog-form
      :visible="dialogVisible"
      :empty="empty"
      :form="form"
      :dialog-form="filteredDialogForm"
      :rules="userRule"
      @handle-cancel="dialogVisible = false"
      @handle-submit="handleSubmit"
    />
    <!--修改密码弹框-->
    <el-dialog
      center
      title="修改密码"
      width="50%"
      class="password-dialog"
      :visible="changePwdDialog"
      :close-on-click-modal="false"
      :before-close="closeChangePwd"
    >
      <el-form
        ref="pwdForm"
        label-width="6em"
        :model="changePwd"
        :rules="passwordRules"
      >
        <el-form-item label="用户：" prop="username">
          <el-input v-model.trim="changePwd.username" disabled />
        </el-form-item>
        <el-form-item label="新密码：" prop="password">
          <el-input
            v-model.trim="changePwd.password"
            type="password"
            placeholder="请输入新密码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="closeChangePwd">取 消</el-button>
        <el-button
          type="primary"
          :disabled="!changePwd.password"
          @click="changePwdSubmit"
        >
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAction } from '@/api/action';
import SearchForm from '@/components/SearchForm'
import DialogForm from '@/components/DialogForm'
import Datagrid from '@/components/Datagrid'

export default {
  name: 'UserManage',
  components: { SearchForm, DialogForm, Datagrid },
  data() {
    // 用户名重复校验
    const validateUsername = (rule, value, callback) => {
      this.uniqueUsername(value, callback);
    };
    return {
      urls: {
        resetPwd: '/api/UserInfoAction/resetPassword', // 重置密码
        uniqueName: '/api/UserInfoAction/checkLoginName', // 验证用户名是否重复
      },
      currentPage: 1,
      pageSize: 10,
      dialogVisible: false,
      empty: '0', // 0 新增，1 修改
      userRule: {
        username: [
          { required: true, message: '此项不能为空', trigger: 'blur', },
          { validator: validateUsername, trigger: 'change', },
        ],
        account: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        groupId: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        // phone: [{ pattern: /^1[3|4|5|8][0-9]\d{8}$/, message: '请输入正确的电话号码', trigger: ['blur', 'change'] }],
        // address: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        // email: [{ pattern: /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/, message: '邮箱格式错误', trigger: ['blur', 'change'] }],
        // company: [{ required: true, message: '此项不能为空', trigger: 'blur' }]
      },
      searchFields: {
        username: '',
        // account: '',
        // phone: '',
        // status: ''
      },
      searchForm: [
        {
          label: '用户名',
          field: 'username'
        },
      ],
      form: {},
      opIndex: 0, // 当前编辑的索引
      dialogForm: [{
        label: '用户名',
        prop: 'username',
      }, {
        label: '昵称', // 登录名
        prop: 'account',
      }, {
        label: '密码',
        prop: 'password',
        type: 'password',
        empty: '0', // 0 新增， 1 编辑
      }, {
        label: '所属角色',
        prop: 'groupId',
        type: 'select',
        options: [],
      }, {
        label: '状态',
        prop: 'status',
        type: 'select',
        options: [{
          label: '启用',
          value: 0
        }, {
          label: '禁用',
          value: 1
        }]
      }, {
        label: '电话号码',
        prop: 'phone',
      }, {
        label: '地址',
        prop: 'address',
        type: 'textarea',
      }, {
        label: '邮箱',
        prop: 'email',
      }, {
        label: '部门',
        prop: 'company',
        type: 'textarea',
      }],
      columns: [{
        label: '用户名',
        width: '180',
        prop: 'username',
      }, {
        label: '昵称', // 登录名
        width: '180',
        prop: 'account',
      }, {
        label: '所属角色',
        prop: 'role.groupName',
      }, {
        label: '电话',
        prop: 'phone',
      }, {
        label: '状态',
        prop: 'status',
        type: 'switch'
      }],
      filteredDialogForm: [],
      changePwdDialog: false,
      changePwd: {
        username: '',
        password: ''
      },
      passwordRules: {
        username: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '此项不能为空', trigger: 'blur' }],
      }
    }
  },
  computed: {
    ...mapGetters(['grouparr', 'userlist', 'userid', 'usertotal', 'pagesize', 'current']),
  },
  created() {
    this.$store.commit('system/SET_ROWS', 10)
    this.$store.commit('system/SET_PAGE', 1)
    this.init()
  },
  methods: {
    init() {
      const obj = {};
      for (const key in this.searchFields) {
        if (Object.hasOwnProperty.call(this.searchFields, key)) {
          const val = this.searchFields[key];
          if (val) {
            obj[key] = val;
          }
        }
      }
      this.$store.dispatch('system/getUserList', obj);
    },
    handleSearch() {
      this.init();
      // console.log('查询', this.searchFields)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.$store.commit('system/SET_ROWS', this.pageSize)
      this.init()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.$store.commit('system/SET_PAGE', this.currentPage)
      this.init()
    },
    /* 验证用户名是否重复 */
    async uniqueUsername(userName, callback) {
      // 新增 || (编辑 修改了用户名)
      if (this.empty === '0' || (this.empty === '1' && this.userlist[this.opIndex].username !== userName)) {
        // TODO: 防抖
        const unique = await getAction(this.urls.uniqueName, { userName }).then(res => {
          return res.data.success;
        })
        if (!unique) {
          callback(new Error('用户名已存在！'));
        } else {
          callback();
        }
        return unique;
      } else {
        callback();
      }
      return true;
    },
    /* 改变开关的值*/
    changeSwitch($event, rows) {
      this.$store.dispatch('system/modifyUser', { userId: rows.userId, status: rows.status })
    },
    /* 删除行*/
    handleDelete(index, rows) {
      this.$confirm('确认删除该行内容？').then(_ => {
        if (this.pageSize < rows.length && this.currentPage > 1) {
          index = (this.currentPage - 1) * this.pageSize + index
        }
        this.$store.commit('system/SET_USERID', rows[index].userId)
        this.$store.dispatch('system/deleteUser').then(res => {
          if (res.data.success) {
            this.$message({ type: 'success', message: '删除成功！' })
            if (rows.length === 1) {
              this.handleCurrentChange(this.currentPage - 1);
            }
            this.init();
          }
        })
      }).catch(_ => { })
    },
    /* 编辑行*/
    handleEdit(index, row) {
      this.empty = '1';
      this.dialogVisible = true;
      this.filterDialogForm();
      this.form = { ...row };
      this.opIndex = index;
    },
    /* 筛选表单 */
    async filterDialogForm() {
      const that = this;
      if (!this.grouparr.length) {
        // 如果没有角色列表，查询
        await this.$store.dispatch('system/getRoleList', { roleStatus: '0' });
      }
      this.dialogForm[3].options = this.grouparr;
      /* 筛选新增/或编辑时才显示的表单 */
      this.filteredDialogForm = this.dialogForm.filter((item) => {
        return item.empty === undefined || item.empty === that.empty;
      })
    },
    /* 新增 */
    handleAdd() {
      this.empty = '0';
      this.dialogVisible = true;
      this.filterDialogForm();
      this.form = {
        username: "",
        account: "",
        password: "",
        groupId: "",
        status: 0,
        phone: null,
        address: null,
        email: null,
        company: null,
        // role: {
        //   addDate: null,
        //   addUser: null,
        //   groupDescription: null,
        //   groupId: "1",
        //   groupName: "admin",
        //   status: 0,
        //   updateDate: null,
        //   updateUser: null,
        // },
      };
    },
    /* 提交 */
    handleSubmit(valid) {
      this.dialogVisible = false;
      if (this.empty === '0') {
        this.form.password = this.$md5(this.form.password);
        this.$store.dispatch('system/addUser', this.form).then(response => {
          if (response.data.success) {
            this.$message({ type: 'success', message: '添加成功！' });
            this.init();
          }
        })
      } else {
        this.$store.dispatch('system/modifyUser', this.form).then(response => {
          if (response.data.success) {
            this.$message({ type: 'success', message: '修改成功！' });
            this.init();
          }
        })
      }
    },
    // 修改密码
    handleChangePwd(index, row) {
      this.changePwdDialog = true;
      this.changePwd.id = row.userId;
      this.changePwd.username = row.username;
    },
    // 关闭/取消
    closeChangePwd() {
      this.changePwdDialog = false;
      this.$refs.pwdForm.resetFields();
    },
    // 确认
    changePwdSubmit() {
      let { id, password } = this.changePwd
      password = this.$md5(password);
      getAction(this.urls.resetPwd, { id, password }).then(res => {
        if (res.data.success) {
          this.$message({ type: 'success', message: '密码修改成功！' })
        }
        this.closeChangePwd();
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.password-dialog {
  .el-form-item {
    display: block;
  }
}
</style>
